package com.taotao.item.listemer;

import java.io.File;
import java.io.FileWriter;
import java.util.HashMap;
import java.util.Map;

import javax.jms.Message;
import javax.jms.MessageListener;
import javax.jms.TextMessage;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.servlet.view.freemarker.FreeMarkerConfigurer;

import com.taotao.item.pojo.Item;
import com.taotao.pojo.TbItem;
import com.taotao.pojo.TbItemDesc;
import com.taotao.service.ItemService;

import freemarker.template.Configuration;
import freemarker.template.Template;
/**
 *  生成freemarker静态化页面的监听器 。 一旦taotao-manager中增加了商品，发送消息到消息队列中，
 *  监听器接收消息，然后立马生成的相应的静态化文件
 *  	对应生成的文件名：商品id+"html"
 * @author created by wq
 * @date   Sep 5, 2017---12:38:10 PM
 * @return
 * @throws Exception<br/>
 *==========History========== <br/>
 * taotao-item-web Sep 5, 2017
 */
public class HtmlFreemarkerListener implements MessageListener{

	@Autowired
	private FreeMarkerConfigurer freeMarkerConfigurer;
	
	@Autowired
	private ItemService itemService;
	
	@Value("${HTML_OUT_PATH}")
	private String HTML_OUT_PATH;
	
	@Override
	public void onMessage(Message message) {
		//强转message为TextMessage
		TextMessage textMessage = (TextMessage) message;
		try {
			String strItemId = textMessage.getText();
			//将商品id强转为long
			Long itemId = new Long(strItemId);
			//通过商品id获得tbItem 
			TbItem tbItem = itemService.getItemByItemId(itemId);
			Item item = new Item(tbItem);
			
			//通过商品id获得tbItemDesc
			TbItemDesc tbItemDesc = itemService.geTbItemDescByItemId(itemId);
			
			//调用freeMarkerConfigurer获取configuration
			Configuration configuration = freeMarkerConfigurer.getConfiguration();
			//通过configuration获得模板
			Template template = configuration.getTemplate("item.htm");
			
			//创建数据集
			Map map = new HashMap<>();
			map.put("item", item);
			map.put("itemDesc",tbItemDesc );
			
			//创建FileWriter
			FileWriter out = new FileWriter(new File(HTML_OUT_PATH + itemId + ".html")) ;
			
			//調用process
			template.process(map, out);
			//释放资源
			out.close();
			
		} catch (Exception e) {
			e.printStackTrace();
		}
	}
}
